<template>
  <div class="main_box" v-loading="pageLoading">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="name" style="width: 1320px; display: block">
              <el-input style="width: 1320px" v-model="filters.name" clearable placeholder="姓名"></el-input>
            </el-form-item>
            <el-form-item prop="hospitalId">
              <el-select v-model="filters.hospitalId" clearable placeholder="医院" filterable>
                <el-option v-for="item in hospitalList" :value="item.hospitalId" :label="item.hospitalName" :key="item.hospitalId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="institutionId">
              <el-select v-model="filters.institutionId" clearable placeholder="医检" filterable>
                <el-option v-for="item in institutionList" :value="item.institutionId" :label="item.institutionName" :key="item.institutionId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="日期"> </el-form-item>

            <el-form-item prop="date">
              <el-date-picker
                v-model="filters.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                unlink-panels
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item prop="transactionId">
              <el-input v-model="filters.transactionId" clearable placeholder="交易号"></el-input>
            </el-form-item>
            <el-form-item prop="applyId">
              <el-input v-model="filters.applyId" placeholder="采样编号"> </el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <el-button plain size="mini" type="success" @click="hanldeClickBatchRefund" v-has="permissionRefund" icon="el-icon-receiving">批量退款</el-button>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="dataList" v-loading="listLoading" :fit="true" highlight-current-row @selection-change="hanldeBatchRefund">
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="applyId" label="采样编号" width="150" align="center"></el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="200" align="center"></el-table-column>
        <el-table-column label="姓名-性别-年龄" width="200" align="center">
          <template slot-scope="scope">
            <div>
              {{ scope.row.name + '-' + (scope.row.sex == 1 ? '男' : '女') + '-' + scope.row.age }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="150"></el-table-column>
        <el-table-column label="医院-科室-医生" width="200" align="center" prop="splicingName"> </el-table-column>
        <el-table-column prop="institutionName" label="医检" width="120" align="center"></el-table-column>
        <el-table-column prop="payAmount" label="支付金额" width="150" align="center"></el-table-column>
        <el-table-column width="150" align="center" label="交易号">
          <template slot-scope="scope">
            <span>
              {{ scope.row.transactionId }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                  class="copy_transactionId"
                  size="mini"
                  icon="el-icon-document-copy"
                  circle
                  plain
                  id="copyBtn"
                  :data-clipboard-text="scope.row.transactionId"
                  @click="copyTransactionId()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionRefund" type="success" plain size="mini" @click="handleRefund(scope.row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import HospitalApi from '@/api/institution/hospital';
import InstitutionApi from '@/api/institution/institution';
import RefundApi from '@/api/finance/refund';
import Clipboard from 'clipboard';
export default {
  name: 'RefundManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      filters: {
        name: '',
        hospitalId: '',
        institutionId: '',
        date: [],
        transactionId: '',
        applyId: '',
      },
      // 被选中的批量退款的id
      applyUserIds: [],
      hospitalList: [],
      institutionList: [],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      permissionRefund: 'SYSTEM_MANAGER_FINANCE_REFUND_LIST_REFUND',
      listLoading: false,
      pageLoading: false, // 页面加载loading

    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  watch: {},
  methods: {
    init() {
      let _this = this;
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      begin.setMonth(begin.getMonth() - 1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      _this.filters.date = [begin, end];
      _this.listData();
      _this.getHospitalList();
      _this.getInstitutionList();
      _this.getTableHeight();

      // _this.listData();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    // 判断属性值是否为空
    valueIsExist(obj) {
      for (let item in obj) {
        if (Array.isArray(obj[item])) {
          if (obj[item].length > 0) {
            return true;
          }
        } else if (obj[item]) {
          return true;
        }
      }
      return false;
    },

    listData() {
      let _this = this;
      if (!_this.valueIsExist(this.filters)) {
        _this.page.pageTotal = 0;
        _this.page.pageNo = 1;
        _this.pageSize = 20;
        _this.dataList = [];
        return;
      }

      // _this.listLoading = true;
      if (_this.filters.date) {
        (this.beginTime = this.$Utils.formatDate(_this.filters.date[0], 'yyyy-MM-dd hh:mm:ss')),
          (this.endTime = this.$Utils.formatDate(_this.filters.date[1], 'yyyy-MM-dd hh:mm:ss'));
      } else {
        this.beginTime = '';
        this.endTime = '';
      }
      var cond = {
        name: this.filters.name,
        hospitalId: this.filters.hospitalId,
        institutionId: this.filters.institutionId,
        beginTime: this.beginTime,
        endTime: this.endTime,
        transactionId: this.filters.transactionId,
        applyId: this.filters.applyId,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
      };
      _this.listLoading = true;
      // 发送请求
      RefundApi.listRefund(cond)
        .then((res) => {
          _this.listLoading = false;
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        // 浏览器尺寸变化响应事件
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    getHospitalList() {
      HospitalApi.getHospitalNameList().then((res) => {
        this.hospitalList = res.data;
      });
    },
    getInstitutionList() {
      InstitutionApi.getInstitutionNameList().then((res) => {
        this.institutionList = res.data;
      });
    },
    // 退款
    handleRefund(row) {
      this.$confirm('确定是否退款？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then((res) => {
        // 调用接口
        RefundApi.refundByApplyUserId({ applyUserId: row.applyUserId }).then((res) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    // 批量退款
    hanldeBatchRefund(val) {
      this.applyUserIds = val.map((item) => item.applyUserId);
    },
    // 点击批量退款
    hanldeClickBatchRefund() {
      if (this.applyUserIds.length == 0) {
        this.$message.error({
          message: '至少选择一项',
        });
        return;
      }
      this.$confirm('确定批量退款？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then((res) => {
        let temp = this.applyUserIds.join(',');
        RefundApi.batchRefund({ applyUserIds: temp }).then((res) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    /**
     * 复制交易号
     */
    copyTransactionId() {
      var clipboard = new Clipboard('.copy_transactionId');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    resetForm() {
      var _this = this;
      _this.$refs.searchForm.resetFields();
      _this.onSearch();
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
  },
};
</script>

<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
<style>
#copyBtn {
  background: none;
  border: none;
}
#copyBtn:hover {
  background: none;
  border: none;
}
</style>
